var url = "https://detail.1688.com/offer/568008515023.html?spm=a262r.11665055.jid1pyu1.2.6aaa48fce67sP0";
var url = "https://detail.1688.com/offer/569650980268.html?spm=b26110380.sw1688.mof001.106.2447689adMDvuR";
var page = require('webpage').create();

//page.captureContent = [ /.*/ ];
page.settings.loadImages = false;
//page.settings.javascriptEnabled=false;

page.onError = function(msg,trace){
	var msgStack = ['ERROR: ' + msg];
	if (trace && trace.length) {
		msgStack.push('TRACE:');
		trace.forEach(function(t) {
			msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
		});
	}
	// uncomment to log into the console 
	//console.error(msgStack.join('\n'));
	//phantom.exit();
};
page.open(url,function(status){
	var analyzeObj = page.evaluate(function(){

		//页面中dom提取的信息=========================================================
		var pageTitle = document.querySelector("#mod-detail-title > h1").textContent;	//页面中标题
		var default_img = document.querySelector("a.box-img > img").getAttribute("src");	//页面中默认图片地址

		var price = document.querySelectorAll("tr.price > td")[1];
		var priceObj = JSON.parse(price.getAttribute('data-range'));
		
		var d_content = document.querySelector("div.mod-detail-purchasing > div.d-content");
		var obj_header = d_content.querySelectorAll("div.obj-header");
		var obj_content = d_content.querySelectorAll("div.obj-content");

		var kvArr = [];
		for(var a=0;a<obj_header.length;a++){
		var kvObj = {};
		var key = obj_header[a].querySelector("span").textContent;  //属性名
		
		var attrName = 'data-unit-config';
		var valArr = obj_content[a].querySelectorAll("div["+attrName+"]");
		if(valArr.length == 0){
			attrName = 'data-sku-config';
			valArr = obj_content[a].querySelectorAll("tr["+attrName+"]");
		}
		var valObjArr = [];
		for(var b=0;b<valArr.length;b++){
			var valObj = JSON.parse(valArr[b].getAttribute(attrName));
			valObjArr.push(valObj);
		}
		kvObj[key] = valObjArr;
		kvArr.push(kvObj);
		}
		
		var obj = {pageTitle:pageTitle,detailAttr:kvArr,defaultImg:default_img,priceObj:priceObj};
		return obj;
	});
	var retObj = {};
	retObj.platform = 'alibaba';
	retObj.analyzeObj = analyzeObj;
	console.log(JSON.stringify(retObj));
	phantom.exit();
});


